//microcommand define color
const render = require("@lnnbot-private/koishi-canvas-svg")
const csstree = require("css-tree")
inject(["canvas"])
option("size", "-s <css-length>", { fallback: "200px" })
signature("<css-background:text>")
action(async ({ session, options: { size } }, input) => {
  var ast = csstree.parse(input, { context: "value" })
  var { error } = csstree.lexer.matchProperty("background", ast)
  if (error) return session.i18n(".invalid")
  const urlNodes = []
  csstree.walk(ast, node => {
    if (node.type === 'Url') urlNodes.push(node)
  })
  const cache = Object.create(null)
  await Promise.allSettled(urlNodes.map(async node => {
    const url = node.value
    const urlWithoutHash = url.split("#", 1)[0]
    const promise = cache[urlWithoutHash] ??= ctx.http(urlWithoutHash, { responseType: "arraybuffer", headers: { accept: "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8" } }).then(r => `data:${r.headers.get("content-type") ?? "application/octet-stream"};base64,${Buffer.from(r.data).toString("base64")}`)
    node.value = await promise + url.slice(urlWithoutHash.length)
  }))
  return render(ctx.canvas, h("svg", { xmlns: "http://www.w3.org/2000/svg", width: size.split(";")[0], height: size.split(";").at(-1) }, h("foreignObject", { x: "0", y: "0", width: "100%", height: "100%" }, h("div", { xmlns: "http://www.w3.org/1999/xhtml", style: "width:100%;height:100%;background:" + csstree.generate(ast) }))).toString())
})
locale("zh-CN", { description: "生成色图", options: { size: "指定宽高" }, messages: { invalid: "输入无效…" } })